package com.cnpc.framework.base.service.impl;


import com.cnpc.framework.base.entity.Org;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.pojo.TreeNode;
import com.cnpc.framework.base.service.OrgService;
import com.cnpc.framework.constant.RedisConstant;
import com.cnpc.framework.utils.TreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("orgService")
public class OrgServiceImpl extends BaseServiceImpl implements OrgService {

    @Override
    public List<TreeNode> getTreeData(String code) {

        // 获取数据
        String key = RedisConstant.ORG_PRE + "tree";

        List<TreeNode> tnlist = null;
        List<Org> orgs = null;
        if (StringUtils.isEmpty(code)) {
            String hql = "from Org order by levelCode asc";
            orgs = this.find(hql);
        }else {
            String sql = "select * from tbl_org where code = :code";
            Map<String, Object> params = new HashMap<>();
            params.put("code", code);
            Org root = getBySql(sql, params,Org.class);
            if (root == null) {
                return null;
            }

            sql = "select * from tbl_org where levelCode like :code order by levelCode asc";
            params.put("code", root.getLevelCode()+"0%");
            orgs = findBySql(sql,params,Org.class);

            if (orgs == null) {
                orgs = new ArrayList<>();
            }
            root.setParentId(null);
            orgs.add(0,root);
        }

        Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>();
        for (Org org : orgs) {
            TreeNode node = new TreeNode();
            node.setText(org.getName());
            node.setId(org.getId());
            node.setParentId(org.getParentId());
            node.setLevelCode(org.getLevelCode());
            nodelist.put(node.getId(), node);
        }
        // 构造树形结构
        tnlist = TreeUtil.getNodeList(nodelist);
        redisDao.save(key, tnlist);
        return tnlist;
    }

    @Override
    public List<TreeNode> getTreeDataByAuth(String userId) {
        Map<String, List<String>> userDataScopeMap = getUserDataScopeMap(userId);
        List<String> deptIds = userDataScopeMap.get("deptList");
        List<String> scopeList = userDataScopeMap.get("scopeList");
        if (deptIds == null || deptIds.size()==0 || scopeList == null || scopeList.size()==0) {
            return null;
        }
        String sql = "select * from tbl_org where id in (:deptIds) order by levelCode asc";
        Map<String, Object> params = new HashMap<>();
        params.put("deptIds", deptIds);
        List<Org> orgs = findBySql(sql,params,Org.class);
        if (orgs != null && orgs.size()>0) {
            if (scopeList.contains("2") || scopeList.contains("3")) {
                orgs.get(0).setParentId(null);
            }

            Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>();
            for (Org org : orgs) {
                TreeNode node = new TreeNode();
                node.setText(org.getName());
                node.setId(org.getId());
                node.setParentId(scopeList.contains("1")?null:org.getParentId());
                node.setLevelCode(org.getLevelCode());
                nodelist.put(node.getId(), node);
            }
            // 构造树形结构
            List<TreeNode> tnlist = TreeUtil.getNodeList(nodelist);
            return tnlist;
        }

        return null;
    }

    public List<Org> getOrgsByCode(String code) {
        String key = RedisConstant.ORG_PRE + code;
        List orgs = redisDao.get(key, List.class);
        if (orgs == null) {
            String hql = "from Org where code='" + code + "'";
            Org org = this.get(hql);
            orgs = this.find("from Org where parentId='" + org.getId() + "' order by levelCode");
            redisDao.add(key, orgs);
            return orgs;
        } else {
            return orgs;
        }
    }

    public boolean referByUser(String orgId) {
        Org org = this.get(Org.class, orgId);
        String sql = "select u.id from tbl_user u left join tbl_org o on u.dept_id=o.id " +
                " where o.levelCode like :levelCode";
        Map<String,Object> param=new HashMap<>();
        param.put("levelCode",org.getLevelCode()+"%");
        List<Map<String, Object>> list=this.findMapBySql(sql,param);
        if(list.isEmpty())
            return false;
        else
            return true;
    }

    @Override
    public Result getOrgNames(String id) {
        //String name=this.redisDao.get("org:"+id);
        //if(StrUtil.isEmpty(name)) {
            Org org=this.get(Org.class,id);
            //if(org.getLevelCode().length()==12){
                //redisDao.save("org:"+id,org.getName());
                return new Result(true,org.getName(),"获取成功");
            //}else{
                //name=getOrgNames(org.getParentId()).getData().toString()+"->"+org.getName();
                //redisDao.save("org:"+id,name);
                //return new Result(true,name,"获取成功");
            //}
        //}else{
           // return new Result(true,name,"获取成功");
        //}
    }

    @Override
    public List<String> getIdsOfOrgAndBellow(String id,String userId) throws Exception{
        String sql = "select levelCode from tbl_org where id =:id";
        Map<String,Object> param=new HashMap<>();
        param.put("id",id);
        if (StringUtils.isNotEmpty(userId)) {
            sql = "select o.levelCode from tbl_user u left join tbl_org o on o.id=u.dept_id where u.id =:id";
            param.put("id",userId);
        }
        String levelCode = getBySql(sql, param);
        if (StringUtils.isNotEmpty(levelCode)) {
            sql ="select id from tbl_org where levelCode like '"+levelCode+"%'";
            List<String> ids = findBySql(sql);
            ids.add(levelCode);
            return ids;
        }
        return null;
    }
}
